// 获取依赖组件 - 使用函数而非变量声明来避免重复声明错误
function getDependencyComponent(componentName) {
    if (typeof window !== 'undefined' && typeof window[componentName] !== 'undefined') {
        return window[componentName];
    }
    return null;
}

// 获取依赖组件的辅助函数，避免重复声明
function getComponents() {
    return {
        UserFormModal: getDependencyComponent('UserFormModal'),
        DataTable: getDependencyComponent('DataTable')
    };
}

// 确保在组件定义前提供基本的Utils对象，防止未定义错误
if (typeof window.Utils === 'undefined') {
    window.Utils = {
        fetchData: async () => ({ status: 0, data: { rows: [], count: 0 } }),
        getApiUrl: (path) => path,
        showAlert: (msg, type) => console.log(`[${type || 'info'}] ${msg}`),
        getUserInfo: () => ({ role: 'ADMIN' })
    };
}

// 获取用户信息函数（保持兼容性）
function getUserInfo() {
    return Utils.getUserInfo();
}

// 教师管理组件
function TeacherManagement() {
    const [teachers, setTeachers] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [searchTerm, setSearchTerm] = React.useState('');
    const [currentPage, setCurrentPage] = React.useState(1);
    const [itemsPerPage, setItemsPerPage] = React.useState(10);
    const [totalCount, setTotalCount] = React.useState(0);
    const [showModal, setShowModal] = React.useState(false);
    const [editingUser, setEditingUser] = React.useState(null);
    const userInfo = getUserInfo();
    
    // 模拟数据，当API不可用时使用
    const mockTeachers = [
        { id: 1, username: 'teacher1', email: 'teacher1@school.com', phone: '13800138001', realName: '张老师', status: 'active', role: 'TEACHER', createTime: new Date().toISOString() },
        { id: 2, username: 'teacher2', email: 'teacher2@school.com', phone: '13800138002', realName: '李老师', status: 'active', role: 'TEACHER', createTime: new Date().toISOString() },
        { id: 3, username: 'teacher3', email: 'teacher3@school.com', phone: '13800138003', realName: '王老师', status: 'inactive', role: 'TEACHER', createTime: new Date().toISOString() },
        { id: 4, username: 'teacher4', email: 'teacher4@school.com', phone: '13800138004', realName: '赵老师', status: 'active', role: 'TEACHER', createTime: new Date().toISOString() },
        { id: 5, username: 'teacher5', email: 'teacher5@school.com', phone: '13800138005', realName: '钱老师', status: 'active', role: 'TEACHER', createTime: new Date().toISOString() }
    ];
    
    // 创建一个ref来跟踪组件的挂载状态
    const isMountedRef = React.useRef(true);
    
    // 组件卸载时设置isMounted为false
    React.useEffect(() => {
        return () => {
            isMountedRef.current = false;
        };
    }, []);

    // 获取教师数据 - 添加isMounted检查以避免内存泄漏
    const fetchTeachers = React.useCallback(async (page = 1, search = '') => {
        setLoading(true);
        try {
            const result = await Utils.fetchData(
                Utils.getApiUrl(`/chm/api/users/teachers?page=${page}&size=${itemsPerPage}&search=${encodeURIComponent(search)}`)
            );
            
            // 检查组件是否仍然挂载
            if (!isMountedRef.current) return;
            
            // 检查response格式
            if (result && result.status === 0) {
                // 根据API实际返回格式，从result.data.rows获取教师数据数组，从result.data.count获取总数
                if (result.data && result.data.rows && Array.isArray(result.data.rows)) {
                    setTeachers(result.data.rows);
                    setTotalCount(result.data.count || result.data.rows.length);
                    console.log('从API加载教师数据成功');
                } else {
                    console.warn('API数据格式不正确，使用模拟数据');
                    setTeachers(mockTeachers);
                    setTotalCount(mockTeachers.length);
                }
            } else {
                // API返回空数据或状态码不为0时使用模拟数据
                console.warn('API返回数据错误或状态码不为0，使用模拟数据');
                setTeachers(mockTeachers);
                setTotalCount(mockTeachers.length);
            }
        } catch (error) {
            // 检查组件是否仍然挂载
            if (!isMountedRef.current) return;
            
            // API调用失败时使用模拟数据
            console.error('从API加载教师数据失败，使用模拟数据:', error);
            Utils.showAlert('获取教师数据失败，请检查网络连接或重新登录', 'error');
            setTeachers(mockTeachers);
            setTotalCount(mockTeachers.length);
        } finally {
            // 检查组件是否仍然挂载
            if (isMountedRef.current) {
                setLoading(false);
            }
        }
    }, [itemsPerPage]);

    // 组件挂载时获取数据
    React.useEffect(() => {
        fetchTeachers(currentPage, searchTerm);
    }, [fetchTeachers, currentPage, searchTerm]);

    // 分页计算
    const totalPages = Math.ceil(totalCount / itemsPerPage);

    // 处理搜索
    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
        setCurrentPage(1);
    };

    // 处理分页
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };
    
    // 处理每页条数变化
    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1); // 重置到第1页
    };

    // 新增教师
    const handleAddTeacher = () => {
        setEditingUser(null);
        setShowModal(true);
    };

    // 编辑教师
    const handleEditTeacher = (teacher) => {
        setEditingUser(teacher);
        setShowModal(true);
    };

    // 处理表单提交
    const handleFormSubmit = async (formData) => {
        const isEditing = !!editingUser;
        try {
            const url = isEditing 
                ? Utils.getApiUrl(`/chm/api/users/${editingUser.id}`)
                : Utils.getApiUrl('/chm/api/users');
            
            const requestData = {
                realName: formData.realName,
                email: formData.email,
                phone: formData.phone,
                username: formData.username, // 使用表单中自动设置的用户名
                role: 'TEACHER' // 明确指定角色为教师（大写）
            };
            
            await (isEditing ? Utils.updateItem(url, requestData) : Utils.createItem(url, requestData));
            
            Utils.showAlert(isEditing ? '教师信息更新成功' : '教师添加成功', 'success');
            setShowModal(false);
            fetchTeachers(currentPage, searchTerm); // 刷新列表
        } catch (error) {
            console.error(isEditing ? '更新教师信息失败:' : '添加教师失败:', error);
            Utils.showAlert(isEditing ? '更新教师信息失败，请检查网络连接' : '添加教师失败，请检查网络连接', 'error');
        }
    };
    
    // 切换教师状态
    const handleToggleStatus = (teacher) => {
        // 新状态
        const newStatus = teacher.status === 'active' ? 'inactive' : 'active';
        
        // 先更新本地状态，提升用户体验
        setTeachers(teachers.map(t => 
            t.id === teacher.id 
                ? { ...t, status: newStatus }
                : t
        ));
        
        // 调用API更新状态
        Utils.updateItem(`/chm/api/users/${teacher.id}/status`, { status: newStatus })
            .catch(error => {
                console.error('更新教师状态失败:', error);
                Utils.showAlert('教师状态更新失败', 'error');
                // 失败时恢复原状态
                fetchTeachers(currentPage, searchTerm);
            });
    };

    // 导入教师
    const handleImportTeachers = () => {
        Utils.showAlert('导入教师功能开发中...', 'info');
    };

    // 删除教师
    const handleDeleteTeacher = async (teacher) => {
        if (confirm(`确定要删除教师 ${teacher.realName} 吗？`)) {
            try {
                const url = Utils.getApiUrl(`/chm/api/users/${teacher.id}`);
                await Utils.deleteItem(url);
                
                Utils.showAlert('教师删除成功', 'success');
                fetchTeachers(currentPage, searchTerm); // 刷新列表
            } catch (error) {
                console.error('删除教师失败:', error);
                Utils.showAlert('删除教师失败，请检查网络连接', 'error');
            }
        }
    };

    // 表格列定义
    const columns = [
        { title: 'ID', field: 'id' },
        { title: '用户名', field: 'username' },
        { title: '姓名', field: 'realName' },
        { title: '邮箱', field: 'email' },
        { title: '手机号', field: 'phone' },
        { 
            title: '状态', 
            value: (teacher) => 
                React.createElement('span', { 
                    className: `inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${teacher.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`
                }, teacher.status === 'active' ? '启用' : '禁用')
        },
        { 
            title: '角色', 
            value: (teacher) => 
                React.createElement('span', { 
                    className: `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        teacher.role === 'ADMIN' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
                    }`
                }, teacher.role === 'ADMIN' ? '管理员' : '教师')
        },
        { 
            title: '创建时间', 
            value: (teacher) => teacher.createTime ? new Date(teacher.createTime).toLocaleDateString('zh-CN') : ''
        }
    ];

    // 操作按钮定义
    const actions = [
        { label: '导入教师', onClick: handleImportTeachers, primary: false },
        { label: '新增教师', onClick: handleAddTeacher, primary: true }
    ];

    // 渲染行操作按钮
    const renderRowActions = (teacher) => 
        React.createElement(React.Fragment, null,
            React.createElement('button', { 
                onClick: () => handleEditTeacher(teacher),
                className: 'text-blue-600 hover:text-blue-900 mr-3'
            }, '编辑'),
            React.createElement('button', { 
                onClick: () => handleToggleStatus(teacher),
                className: 'text-yellow-600 hover:text-yellow-900 mr-3'
            }, teacher.status === 'active' ? '禁用' : '启用'),
            React.createElement('button', { 
                onClick: () => handleDeleteTeacher(teacher),
                className: 'text-red-600 hover:text-red-900'
            }, '删除')
        );
    
    // 退出登录
    const logout = () => {
        try {
            localStorage.removeItem('auth.loggedIn');
            localStorage.removeItem('auth.token');
            localStorage.removeItem('auth.userId');
            localStorage.removeItem('auth.username');
            localStorage.removeItem('auth.realName');
            localStorage.removeItem('auth.email');
        } catch (e) {}
        window.location.href = 'login.html';
    };

    // 确保teachers是数组格式
    const safeTeachers = Array.isArray(teachers) ? teachers : [];
    
    // 获取组件依赖
    const { UserFormModal, DataTable } = getComponents();
    
    // 检查必要组件是否可用
    if (!UserFormModal || !DataTable) {
        console.warn('必要组件未加载完成:', {
            UserFormModal: !!UserFormModal,
            DataTable: !!DataTable
        });
        
        // 返回加载中状态
        return React.createElement('div', { className: 'p-8 bg-white rounded-lg shadow-md mx-auto max-w-md' },
            React.createElement('div', { className: 'text-center' },
                React.createElement('div', { className: 'animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto mb-4' }),
                React.createElement('h2', { className: 'text-xl font-bold text-gray-800' }, '加载组件中...'),
                React.createElement('p', { className: 'text-gray-600 mt-2' }, '请稍等，组件正在加载。如果长时间未完成，请刷新页面重试。'),
                React.createElement('button', {
                    onClick: () => window.location.reload(),
                    className: 'mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600'
                }, '刷新页面')
            )
        );
    }
    
    return React.createElement(React.Fragment, null,
        // 用户表单模态框
        React.createElement(UserFormModal, {
            isOpen: showModal,
            onClose: () => setShowModal(false),
            onSubmit: handleFormSubmit,
            user: editingUser,
            role: 'teacher'
        }),
        
        // 主内容区域
        React.createElement('div', { className: 'flex-1 overflow-auto' },
            React.createElement('div', { className: 'p-6' },
                React.createElement(DataTable, {
                    title: '教师管理',
                    description: '管理系统中所有教师账户信息',
                    columns: columns,
                    data: safeTeachers,
                    loading: loading,
                    searchValue: searchTerm,
                    onSearch: handleSearch,
                    searchPlaceholder: '搜索用户名、姓名、邮箱或手机号...',
                    currentPage: currentPage,
                    totalPages: totalPages,
                    totalCount: totalCount,
                    itemsPerPage: itemsPerPage,
                    onPageChange: handlePageChange,
                    onItemsPerPageChange: handleItemsPerPageChange,
                    actions: actions,
                    renderRowActions: renderRowActions
                })
            )
        )
    );
}

// 在组件定义后立即注册到全局作用域
// 使用自执行函数确保即使在非浏览器环境下也不会报错
(function() {
    if (typeof window !== 'undefined') {
        // 确保在TeacherManagement组件定义后立即暴露到全局作用域
        window.TeacherManagement = TeacherManagement;
        
        // 创建一个自定义事件通知组件加载完成
        try {
            const event = new CustomEvent('TeacherManagementLoaded', {
                detail: {
                    componentName: 'TeacherManagement',
                    loadedAt: new Date().toISOString()
                }
            });
            window.dispatchEvent(event);
            console.log('TeacherManagement组件已成功加载并注册到全局作用域');
        } catch (e) {
            // 如果CustomEvent不可用，使用简单的标志变量
            window.TeacherManagementLoaded = true;
        }
        
        // 尝试自动渲染组件到root元素（当直接访问teacher-management.html时）
        setTimeout(() => {
            const rootElement = document.getElementById('root');
            if (rootElement && rootElement.children.length === 0 && 
                typeof React !== 'undefined' && typeof ReactDOM !== 'undefined') {
                console.log('检测到root元素为空，尝试自动渲染TeacherManagement组件');
                try {
                    ReactDOM.render(
                        React.createElement(TeacherManagement),
                        rootElement
                    );
                    console.log('TeacherManagement组件自动渲染成功');
                } catch (renderError) {
                    console.error('TeacherManagement组件自动渲染失败:', renderError);
                    // 显示错误信息到界面
                    if (rootElement && !rootElement.hasChildNodes()) {
                        rootElement.innerHTML = `
                            <div class="p-8 bg-white rounded-lg shadow-md mx-auto max-w-md">
                                <div class="text-center">
                                    <div class="text-red-500 text-4xl mb-4">⚠️</div>
                                    <h2 class="text-xl font-bold text-gray-800">组件加载错误</h2>
                                    <p class="text-gray-600 mt-2">TeacherManagement组件渲染失败，请刷新页面重试。</p>
                                    <button onclick="window.location.reload()"
                                            class="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
                                        刷新页面
                                    </button>
                                </div>
                            </div>
                        `;
                    }
                }
            }
        }, 100);
    }
})();